package com.zhi.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.zhi.entity.Dictionary;
import com.zhi.service.DictionaryService;
import com.zhi.util.PageUtil;

@Controller
public class DictionaryController {

    Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	DictionaryService dictionaryService;

    @RequestMapping("/toDictionary")
    public String toDictionary(Model model,PageUtil pageUtil) {
    	
    	//1、初始化分页工具
    	pageUtil = PageUtil.init(pageUtil);
    	Sort sort = Sort.by("codeType");
    	Pageable pageable = PageRequest.of(pageUtil.getPageIndex()-1, pageUtil.getSize(),sort);
    	
    	//2、查询分页数据
    	Page<Dictionary> pageList=dictionaryService.getEntityList(pageable);
    	List<Dictionary> list = pageList.getContent();
    	
    	//3、设置总页数
    	pageUtil.setTotalPages(pageList.getTotalPages());
    	
    	//4、返回前台数据
        model.addAttribute("dicts", list);
        model.addAttribute("pageUtil", pageUtil);
        
        return "dictionary/list";
    }
    
    @RequestMapping("/dict/delete")
    public String deleteById(Integer id) {
    	dictionaryService.delete(id);
    	return "redirect:/toDictionary";
    }
    
    @RequestMapping("/dict/toAdd")
    public String toAdd() {
    	return "dictionary/add";
    }
    
    @RequestMapping("/dict/add")
    public String add(Dictionary dictionary) {
    	dictionaryService.save(dictionary);
    	return "redirect:/toDictionary";
    }
    
    @RequestMapping("/dict/toEdit")
    public String toEdit(Model model,Integer id) {
    	Dictionary dictionary = dictionaryService.getOne(id);
    	model.addAttribute("dict", dictionary);
    	return "dictionary/edit";
    }
    
    @RequestMapping("/dict/update")
    public String update(Dictionary dictionary) {
    	dictionaryService.save(dictionary);
    	return "redirect:/toDictionary";
    }
	
}
